package com.alogic.remote.xscript.auth;

import com.alogic.remote.Request;
import com.alogic.remote.xscript.RequestHandler;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

/**
 * Http Basic 认证
 *
 * @since 1.6.12.54 [20191212]
 */
public class WithHttpBasicAuth extends RequestHandler {
    protected String $authString;
    protected boolean isRaw = true;

    public WithHttpBasicAuth(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        $authString = PropertiesConstants.getRaw(p,"auth",$authString);
        isRaw = PropertiesConstants.getBoolean(p,"auth.raw",isRaw);
    }

    @Override
    protected void onExecute(final Request req, final XsObject root, final XsObject current, final LogicletContext ctx,
                             final ExecuteWatcher watcher) {
        String authString = PropertiesConstants.transform(ctx,$authString,"");
        if (StringUtils.isNotEmpty(authString)) {
            if (isRaw) {
                req.setHeader("Authorization", String.format("Basic %s", Base64.encodeBase64String(authString.getBytes())));
            }else{
                req.setHeader("Authorization", String.format("Basic %s", authString));
            }
        }else{
            log("AuthString is null,ignored",LOG_WARNING,ctx);
        }
    }
}